<?php
/**
 * Template for Mage_Adminhtml_Block_Catalog_Product_Edit
 */
?>

<div class="content-header" id="vendor_content_header">
    <h3 class="icon-head head-products"><?php echo $this->getHeader() ?></h3>
    <p class="content-buttons form-buttons" ><?php echo $this->getBackButtonHtml() ?>
    <?php echo $this->getCancelButtonHtml() ?>
    <?php if($this->getProductId()): ?>
        <?php echo $this->getDeleteButtonHtml() ?>
        <?php if($this->getProductSetId() && $this->getIsConfigured()): ?>
            <?php echo $this->getDuplicateButtonHtml() ?>
        <?php endif; ?>
    <?php endif; ?>
    <?php if($this->getProductSetId() && $this->getIsConfigured()): ?>
        <?php echo $this->getSaveButtonHtml() ?>
        <?php echo $this->getSaveAndEditButtonHtml() ?>
        <?php if(in_array($this->getProduct()->getApproval(),array(VES_VendorsProduct_Model_Source_Approval::STATUS_NOT_SUBMITED, VES_VendorsProduct_Model_Source_Approval::STATUS_UNAPPROVED))):?>
        	<?php echo $this->getChildHtml('submit_button');?>
        <?php endif;?>
    <?php endif; ?>
    </p>
</div>
<form action="<?php echo $this->getSaveUrl() ?>" method="post" id="product_edit_form" enctype="multipart/form-data">
    <?php echo $this->getBlockHtml('formkey')?>
    <div style="display:none"></div>
</form>
<script type="text/javascript">
//<![CDATA[
    var productTemplateSyntax = /(^|.|\r|\n)({{(\w+)}})/;
    var productForm = new varienForm('product_edit_form', '<?php echo $this->getValidationUrl() ?>');
    productForm._processValidationResult = function(transport) {
        var response = transport.responseText.evalJSON();
        if (response.error){
            if (response.attribute && $(response.attribute)) {
                $(response.attribute).setHasError(true, productForm);
                Validation.ajaxError($(response.attribute), response.message);
                if (!Prototype.Browser.IE){
                    $(response.attribute).focus();
                }
            }
            else if ($('messages')) {
                $('messages').innerHTML = '<ul class="messages"><li class="error-msg"><ul><li>' + response.message + '</li></ul></li></ul>';
            }
        }
        else{
            productForm._submit();
        }
    };
    function saveAndContinueEdit(urlTemplate) {
        var template = new Template(urlTemplate, productTemplateSyntax);
        var url = template.evaluate({tab_id:product_info_tabsJsTabs.activeTab.id});
        productForm.submit(url);
    }
    function setSettings(urlTemplate, setElement, typeElement) {
        var template = new Template(urlTemplate, productTemplateSyntax);
        setLocation(template.evaluate({attribute_set:$F(setElement),type:$F(typeElement)}));
    }

     function setSuperSettings(urlTemplate, attributesClass, validateField) {
        var attributesFields = $$('.' + attributesClass);
        var attributes = Form.serializeElements(attributesFields, true).attribute;
        if(typeof attributes == 'string') {
            attributes = [attributes];
        }

        if(!attributes) {
            $(validateField).value = 'no-attributes';
        } else {
            $(validateField).value = 'has-attributes';
        }
        
        if (productForm.validator.validate()) { 
            var template = new Template(urlTemplate, productTemplateSyntax);
            
            var url = template.evaluate({
                attributes: encode_base64(attributes.join(',')).replace(new RegExp('/','g'),'%2F').replace(new RegExp('=','g'),'%3D')
            });
            
            setLocation(url);
         } 
    }

    function checkMaxLength(Object, MaxLen)
    {
        if (Object.value.length > MaxLen-1) {
            Object.value = Object.value.substr(0, MaxLen);
        }
        return 1;
    }

Event.observe(window, 'load', function() {
    var objName = '<?php echo $this->getSelectedTabId() ?>';
    if (objName) {
        obj = $(objName);
        //IE fix (bubbling event model)
        product_info_tabsJsTabs.setSkipDisplayFirstTab();

        /*lie*/
        if(!document.getElementById('simple_product'))
        {
       	 	product_info_tabsJsTabs.showTabContent(obj);
        }
       
    }
    Product.AttributesBridge.setTabsObject(product_info_tabsJsTabs);
});

Validation.addAllThese([
    ['validate-super-product-attributes', '<?php echo Mage::helper('catalog')->__('Please select one or more attributes.') ?>', function(v) {
                return (v != "no-attributes");
            }]]);
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
	/*显示所有的组*/
window.onload = function()
{
	var productType = '<?php echo $this->getRequest()->getParam('type'); ?>';
	if(productType == 'configurable' )
	{
		if(!document.getElementById('simple_product')) /*配置产品未保存时，不显示Associated Product这一列*/
		{
			loadCategories(); /* 加载分类 */
			displayFrom('product_edit_form', 'block'); /* 显示所有product_info_tabs */
			hideEle('product_info_tabs_configurable_content'); /* 隐藏此product_info_tabs */
			hideEle('product_info_tabs_websites_content'); /* 隐藏此product_info_tabs */
			hideEle('product_info_tabs_inventory_content'); /* 隐藏此product_info_tabs */
			hideButton('Save');/* 隐藏save按钮 */
		}
		else
		{
			displayFrom('product_edit_form', 'none'); /* 隐藏所有product_info_tabs */
			showEle('product_info_tabs_configurable_content'); /* 显示此product_info_tabs */
			hideButton('Save and Continue Edit'); /* 隐藏Save and Continue Edit按钮 */
			hideButton('Duplicate');/* 隐藏Duplicate按钮 */
		}
	}
	else if(productType == 'simple')
	{
		loadCategories(); /* 加载分类 */
		displayFrom('product_edit_form', 'block'); /* 显示所有product_info_tabs */
		hideEle('product_info_tabs_configurable_content'); /* 隐藏此product_info_tabs */
		hideEle('product_info_tabs_websites_content'); /* 隐藏此product_info_tabs */
		hideButton('Save and Continue Edit'); /* 隐藏Save and Continue Edit按钮 */
	}
	else
	{
		loadCategories(); /* 加载分类 */
		displayFrom('product_edit_form', 'block'); /* 显示所有product_info_tabs */
		hideEle('product_info_tabs_configurable_content'); /* 隐藏此product_info_tabs */
		hideEle('product_info_tabs_websites_content'); /* 隐藏此product_info_tabs */
	}
		
}	



	
	function loadCategories()
	{
		var productInfoTabsCategories = document.getElementById('product_info_tabs_categories');
		if(productInfoTabsCategories) {productInfoTabsCategories.click();}
	}
	function displayFrom(idName, customStatus)
	{
		var fromObj = document.getElementById(idName);
		if(fromObj)
		{
			var subNodeObj= fromObj.children;
			for(var i=0;i<subNodeObj.length;i++) {subNodeObj[i].style.display = customStatus;}
		}
	}
	function showEle(idName)
	{
		var showElement = document.getElementById(idName);
		if(showElement) {showElement.style.display = 'block';}
	}
	function hideEle(idName)
	{
		var hideElement = document.getElementById(idName);
		if(hideElement) {hideElement.style.display = 'none';}
	}
	function hideButton(buttonTitle)
	{
		var vendorContentHeader = document.getElementById('vendor_content_header');
		if(vendorContentHeader)
		{
			headerAllButton = vendorContentHeader.getElementsByTagName('button');
			for (var i = 0; i < headerAllButton.length; i++)
			{
				if(headerAllButton[i].title == buttonTitle) {headerAllButton[i].style.display = 'none';}
			}
		}
	}
//]]>
</script>


<script type="text/javascript">

//<![CDATA[
/*lie 2016-03-02 */
Event.observe(window, 'load', function() 
{
	/*General*/
	hiddenRow('fb_product');
	hiddenRow('news_from_date');
	hiddenRow('news_to_date');
	hiddenRow('url_key');
	hiddenRow('country_of_manufacture');
	hiddenRow('is_returnable');
	hiddenRow('weight');
	hiddenRow('status');
	hiddenRow('em_featured');
	hiddenRow('em_deal');
	hiddenRow('em_hot');
	hiddenRow('common_reasons');
	hiddenRow('yml');
	hiddenRow('yandex_market_product_category');
	hiddenRow('pulscen');
	
	/*Prices*/
	hiddenRow('tax_class_id');
	hiddenRow('tiers_table');
	hiddenRow('msrp');
	/*Base*/
	hiddenRow('common_other_shipping_type');
	hiddenRow('common_publish_platform');
	hiddenRow('common_shipping_method');
	hiddenRow('common_warehouse_code');
	hiddenRow('common_dimensional_weight');
	/*Inventory*/
	hiddenRow('inventory_manage_stock');
	hiddenRow('inventory_min_qty');
	hiddenRow('inventory_min_sale_qty');
	hiddenRow('inventory_max_sale_qty');
	hiddenRow('inventory_is_qty_decimal');
	hiddenRow('inventory_notify_stock_qty');
	hiddenRow('inventory_enable_qty_increments');
	hiddenRow('inventory_backorders');
	/*associated products*/
	hiddenRow('simple_product_visibility');
	hiddenRow('simple_product_status');
	<?php 
        $vendorCollection = Mage::getModel('vendors/vendor')->load(Mage::getSingleton('vendors/session')->getId());
	    $warehouseCode = str_replace('S', 'SW', $vendorCollection->getVendorId());
	?>
	setTextDefaultValueById('common_warehouse_code', '<?php echo  $warehouseCode;?>');
	setCheckboxDefaultValueById('product_website_1');
	setSelectDefaultValueByOptionValue('tax_class_id','0');
	setSelectDefaultValueByOptionValue('inventory_stock_availability','1');
	setSelectDefaultValueByOptionValue('simple_product_visibility','1');
	setSelectDefaultValueByOptionValue('simple_product_status','2');
	setYNSelectDefaultValueByOptionValue('status','2');

	/*只读*/
	readonlyText('price');
	readonlyText('special_price');
	readonlyText('cost');

	/*特价*/
	specialPrice('common_supplier_special_price');
	specialPrice('cost');

	/*默认选中configurable_attributes的Use default*/
	checkedConfigurableAttribute();
	/*隐藏Create Simple Associated Product*/
	hideCreateSimpleAssociatedProduct()
	/*运费查询*/
	shippingQuery('common_weight');
	shippingQuery('common_package_length');
	shippingQuery('common_package_width');
	shippingQuery('common_package_height');
	shippingQuery('common_shipping_type');
	shippingQuery('common_supply_price');
	shippingQuery('common_dimensional_weight');

});


	/*******************************/
	<?php
	/*如果当前产品类型为configurable, 则需要更改inventory_manage_stock的值为no*/

	if(Mage::app()->getRequest()->getParam('type'))
	{
		$productType = Mage::app()->getRequest()->getParam('type');
	}
	else
	{
	    
		if(Mage::app()->getRequest()->getParam('id'))
		{
			$product = Mage::getModel('catalog/product')->load(Mage::app()->getRequest()->getParam('id'));
			$productType = $product->getTypeId(); 
		}
		else 
		{
		    $productType = '';
		}
	}

	if($productType): 
	?>
	var productType = "<?php echo $productType;?>";
	if(productType == 'configurable')
	{
		var obj1 = document.getElementById('inventory_use_config_manage_stock');
		var obj2 = document.getElementById('inventory_manage_stock');
		if(obj1 && obj2)
		{
			obj1.checked  = false;
			obj2.disabled = false;
			for(var i=0;i<obj2.options.length;i++)
			{
				if(obj2.options[i].value == '0')
				{
					obj2.options[i].selected=true;
				}
			}

			hiddenLeftTabs('Inventory');
			hiddenLeftTabs('Склад');
		}
	}
	<?php endif; ?>




	/*******************************************************/
	/* 特价价格填写完之后，自动加上运费 */
	function specialPrice(idName)
	{
		addRemark('special_price', 'Special Price = (Supplier Special Price + Cost Price) / 0.95');
		var idObject = document.getElementById(idName);
		if (idObject)
		{
			idObject.onblur=function()
			{

				/*必需这两个选项都有值，才触发给specialPrice填写价格。*/
				var supplierSpecialPrice = checkHasValue('common_supplier_special_price');
				var cost  = checkHasValue('cost');
				
        		if(supplierSpecialPrice && cost){
					var specialPrice = document.getElementById('special_price');
					specialPrice.value = ((Number(supplierSpecialPrice) + Number(cost)) / 0.95).toFixed(2); 
				}else{
					var specialPrice = document.getElementById('special_price');
					specialPrice.value = '';
				}
			}
		}
	}

	/*加备注*/
	function addRemark(idName, Text)
	{
		var idObject = document.getElementById(idName);
		if(idObject)
		{
			var createDiv=document.createElement("div");
			createDiv.setAttribute("id", "massage_" + idName);
			createDiv.innerHTML=Text;
			if(document.getElementById("massage_" + idName) == null)
			{
				idObject.parentNode.appendChild(createDiv);
			}
		}
		
	}

	/*只读*/
	function readonlyText(idName)
	{
		var idObject = document.getElementById(idName);
		if(idObject) {idObject.readOnly = true;idObject.style.backgroundColor = '#EFEFEF';}
	}
	
	/* 隐藏tr */
	function hiddenRow(idName)
	{
		var idObject = document.getElementById(idName);
		if(idObject)
		{
			var parentObject = idObject.parentNode.parentNode; /* 获取ID的两层父级 */
			if(parentObject)
			{
				parentObject.style.display = 'none';
			}
		}
	}

	function hiddenLeftTabs(titleName)
	{
		var idObject = document.getElementById('product_info_tabs');
		if(idObject)
		{
			var liSets = idObject.getElementsByTagName('li');
			if(liSets)
			{
				for (var i = liSets.length - 1; i >= 0; i--)
				{
					var aSets = liSets[i].getElementsByTagName('a');
					if(aSets)
					{
						for (var j = aSets.length - 1; j >= 0; j--)
						{
							if(aSets[j].title && aSets[j].title == titleName)
							{
								liSets[i].style.display = 'none';
							}
						}
					}
				}
			}
		}
	}


	/*设置text初始值*/
	function setTextDefaultValueById(idName, defaultValue)
	{
		var idObject = document.getElementById(idName);
		if(idObject)
		{
			idObject.value = defaultValue;
		}
	}


	/*设置select初始值*/
	function setSelectDefaultValueByOptionValue(selectId, optionValue)
	{
		var selectObject = document.getElementById(selectId);
		if(selectObject)
		{
			if(selectObject.value == '') /*如果没有选过，则选中默认值*/
			{
				for(var i=0;i<selectObject.options.length;i++)
				{
					if(selectObject.options[i].value == optionValue)
					{
						selectObject.options[i].selected=true;
					}
				}
			}
		}
	}

	/*设置yes/no,enabled/disabled类型的select初始值*/
	function setYNSelectDefaultValueByOptionValue(selectId, optionValue)
	{
		var selectObject = document.getElementById(selectId);
		if(selectObject)
		{
			for(var i=0;i<selectObject.options.length;i++)
			{
				if(selectObject.options[i].value == optionValue)
				{
					selectObject.options[i].selected=true;
				}
			}
		}
	}

	/*设置checkbox初始值*/
	function setCheckboxDefaultValueById(idName)
	{
		var idObject = document.getElementById(idName);
		if(idObject)
		{
			idObject.checked = true;	
		}
	}


	/*默认选中configurable_attributes的Use default*/
	function checkedConfigurableAttribute()
	{
		var configurableAttribute = document.getElementById('configurable_attributes');
		if(configurableAttribute)
		{
			var attrCheckbox = configurableAttribute.getElementsByTagName('input');
			for(var i=0; i<attrCheckbox.length; i++) { attrCheckbox[i].checked = true; }
		}
	}
  
	/*隐藏Create Simple Associated Product*/
	function hideCreateSimpleAssociatedProduct()
	{
		var configurableContent = document.getElementById('product_info_tabs_configurable_content');
		if(configurableContent) {configurableContent.firstChild.style.display = 'none';}
	}
	
	/*查询运费方法*/

	function shippingQuery(idName)
	{
		var idObject = document.getElementById(idName);
		if (idObject)
		{
			idObject.onblur=function()
			{

				/*必需这六个选项都有值，才触发运费查询的ajax请求。*/
				var vendorWeight 		= checkHasValue('common_weight');
				var vendorPackageLength = checkHasValue('common_package_length');
				var vendorPackageWidth  = checkHasValue('common_package_width');
				var vendorPackageHeight = checkHasValue('common_package_height');
				var vendorShippingType  = checkHasValue('common_shipping_type');
				vendorSupplyPrice   	= checkHasValue('common_supply_price');

				if(vendorWeight && vendorPackageLength && vendorPackageWidth && vendorPackageHeight 
					&& vendorShippingType && vendorSupplyPrice)
				{
					var packageWeight = ((vendorPackageLength * vendorPackageWidth * vendorPackageHeight) / 12000).toFixed(2);
					if(vendorShippingType == '14') /* 判断是否是电商专递，如果不是则直接取真实重量 */
					{
						if(packageWeight > vendorWeight) /*体积重>重量，为轻抛物，按体积重算*/
						{
							var finalWeight   = packageWeight;
						}
						else
						{
							var finalWeight   = vendorWeight;
						}
					}
					else
					{
						var finalWeight   = vendorWeight;
					}
					console.log('finalWeight = ' + finalWeight);
					
					var Url = "<?php echo Mage::getUrl("shippingquery/vendor/query/") ?>";
					var vendorId = "<?php echo Mage::getSingleton('vendors/session')->getVendor()->getId();?>";
					new Ajax.Request(Url, 
					{
						method: 'post',
						parameters: {weight: finalWeight, shippingcode: vendorShippingType, vendorid: vendorId},
						onSuccess: function(transport) {
							var returnPrice = transport.responseText
							document.getElementById('cost').value = returnPrice;
							document.getElementById('price').value = ((Number(returnPrice) + Number(vendorSupplyPrice)) / 0.95).toFixed(2);
							
							/*设置特价*/
							var commonSupplierSpecialPrice = checkHasValue('common_supplier_special_price');
							if(commonSupplierSpecialPrice){
								document.getElementById('special_price').value = ((Number(returnPrice) + Number(commonSupplierSpecialPrice)) / 0.95).toFixed(2);
							}
						}
					});
				}
	    	}
		
		}
	}

	function checkHasValue(idName)
	{	
		var idObject = document.getElementById(idName);
		
		if(idObject.value != '')
		{
			
			if(idName == 'common_weight')
			{
				/*如果是common_weight,要把值赋给weight选项*/
				if(document.getElementById('weight'))
				{
					document.getElementById('weight').value = idObject.value;
				}

				/*同时检测是否有超过2kg，超过就不能选小包类型*/
				if(Number(idObject.value) > 2)
		    		{
		    			idObject1 = document.getElementById('common_shipping_type');
                        
			            for(var i=0;i<idObject1.options.length;i++)
			            {
			                if(idObject1.options[i].value == '14')
			                {
			                    idObject1.options[i].selected = true;
			                }
			                else
			                {
			                    idObject1.options[i].disabled = true;
			                }
			                
			            }
				        
		    			var createDiv=document.createElement("div");
		    			createDiv.setAttribute("id", "Massage_onlyselect_common_shipping_type");
		    			createDiv.setAttribute("class", "validation-advice");
						createDiv.innerHTML="Weight is greater than 2kg. Only select Ecommerce Express.";
						if(document.getElementById("Massage_onlyselect_common_shipping_type") == null)
						{
							idObject1.parentNode.appendChild(createDiv);
						}
						
		    		}
		    		else
		    		{
		    			idObject1 = document.getElementById('common_shipping_type');
                        
			            for(var i=0;i<idObject1.options.length;i++)
			            {
			                idObject1.options[i].disabled = false;
			            }

		    			massageDiv = document.getElementById("Massage_onlyselect_common_shipping_type");
						if( massageDiv != null)
						{
							massageDiv.parentNode.removeChild(massageDiv);
						}
		    		}
			}

			/*检测供应商价格的值是否大于0*/
			if(idName == 'common_supply_price')
			{
				idObject1 = document.getElementById('common_supply_price');
				if(idObject1)
				{
					var oldClassName = idObject1.className;
					if(idObject1.value)
					{
						if(idObject1.value <= 0)
						{

						}
					}
				}
			}


			return idObject.value;
		}
		else
		{
			return false;
		}
	}

//]]>
</script>


<!-- /*you 是否带电和带电证书有效期关联功能 2016-4-11*/ -->
<script type="text/javascript">
    //<![CDATA[
    var weightject = document.getElementById('common_is_charged');
    var codeject   = document.getElementById('common_msds');

    var labelject  = document.getElementsByTagName("label");
    var labelspan = "<span class='required'> *</span>";
    if(weightject)
    {
        weightject.onblur=function()
        {
            var weightjectValue = weightject.value;

            if(weightjectValue == 1)
            {
                if(codeject)
                {   
                    var beforeClass     = codeject.className;
                    if(beforeClass.indexOf('required-entry')<0)
                    {
                        var beforemyClass  = beforeClass+' required-entry';
                        codeject.className = beforemyClass;
                    }
                    var labelhtml      = getLabelForValue(labelject,codeject);
                    var labelspanval   = labelhtml.lastChild;
                    if(labelspanval.nodeName != 'SPAN'){
                        var labeltext      = labelhtml.innerHTML;
                        labelhtml.innerHTML= labeltext+labelspan;
                    }
                }
            }else if(weightjectValue ==0){
                if(codeject)
                {
                    codeject.className = codeject.className.replace(' required-entry', '');
                    var labelhtml      = getLabelForValue(labelject,codeject);
                    var labelspanval   = labelhtml.lastChild;
                    if(labelspanval.nodeName == 'SPAN'){
                        labelhtml.removeChild(labelspanval);
                    }
                }
            }
        }
    }
    function getLabelForValue(labelject,codeject)
    {
        for(i=0;i<labelject.length;i++)
        {
            var forvalue=labelject[i].getAttributeNode("for").value;
            if(forvalue==codeject.id)
            {                         
                return labelject[i];
            }
        }
    }
    //]]>
</script>
<!-- /*you 是否带电和带电证书有效期关联功能 2016-4-11*/ -->
